<?php

namespace Frieza\Modules\CommunityMcn\Controllers;

use App\Exceptions\InputErrorException;
use App\Http\Controllers\Controller;
use Doraemon\service\CommunityMcn\AdminRole;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Layout\Content;
use Doraemon\model\CommunityMcn\Brief;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\service\CommunityMcn\Brief as sBrief;
use Doraemon\tools\ParamsCheck;

class BriefInfoController extends Controller
{
    public static $isBusiness = false;

    public function create(Content $content, $id = 0)
    {
        $info = [];
        $isBusiness = AdminRole::isBusiness();
        if ($id) {
            $info = Brief::getByid($id);
            $info['expect_start_time'] = date('Y-m-d', $info['expect_start_time']);
            $info['expect_end_time'] = date('Y-m-d', $info['expect_end_time']);
            $info['one_price_num'] = $info['one_price_num']/100;
            $info['price_goods_price'] = $info['price_goods_price']/100;
        }
        $form = new Form($info);
        $form->hidden('id', 'brief ID');
        $form->hidden('status', '状态');
        $form->text('project_name', '项目名称')->required();
        $form->radioButton('brand_inner', '站内/站外')->options(Brief::BRAND_INNER_LIST)->required()
            ->when('=', 1, function ($form) {
                $brandList = sBrief::getBrandList();
                $form->select('popularize_brand_id', '推广品牌')->options($brandList);
            })->when('=', 2, function ($form) {
                $form->text('popularize_brand_name', '推广品牌');
            });
        $form->text('store_id', '店铺ID');
        $form->text('store_name', '店铺名称');
        $form->text('order_id', '订单ID')->readonly()->default('系统生成');
        $form->multipleSelect('collaborative_area', '合作领域')->options(Brief::AREA_LIST)->required();
        $form->text('goods_id', '主推商品ID')->required();
        $form->text('goods_trait', '主推商品卖点')->placeholder('请输入商品卖点');
        $form->text('popularize_product', '推广产品')->required();
        $form->textarea('product_url', '产品链接')->required();
        $form->radioButton('purpose', '传播目的')->options(Brief::PURPOSE_LIST)->required()
            ->when('=', 4, function ($form) {
                $form->text('purpose_other', '其他传播目的');
            });
        $form->radio('cooperate_style', '合作方式')->options(Brief::COOPERATE_STYLE_LIST)->required();
        $form->dateRange('expect_start_time', 'expect_end_time', '期望发布时间')->required();
        $form->radioButton('price_style', '报价方式')->options(Brief::PRICE_STYLE_LIST)->required()
            ->when('=', 1, function ($form) {
                $form->select('one_price_type', '一口价报价方式')->options(Brief::ONE_PRICE_TYPE_LIST);
                $form->text('one_price_num', '一口价（元）');
            })
            ->when('=', 2, function ($form) {
                $form->text('price_goods_num', '主推商品提供件数');
                $form->text('price_goods_price', '主推商品提供价格（元）');
            });
        $form->radio('content_type', '上传内容类型')->options(Brief::CONTENT_TYPE_LIST)->required();
        $form->textarea('words_demand', '文字需求');
        $form->textarea('pictures_demand', '图片需求');
        $form->textarea('videos_demand', '视频需求');
        $form->textarea('creator_require', '创作者要求')->required();
        $form->textarea('remarks', '备注')->required();
        Admin::script($this->saveScript());
        $form->disableSubmit();
        $form->disableReset();
        if ($id && !$isBusiness && $info['status'] == Brief::STATUS_CHECK) {
            $url = '/admin/communityMcn/suggestion/create?b_id=' . $id;
            $form->html('<div style="text-align:center;padding-top: 30px" >
                    <a href="' . $url . '"><input class="btn btn-sm btn-soundcloud " value="添加修改意见" style="margin-right: 100px;width: 130px;height: 35px"></a>
                    <input class="btn btn-sm btn-success " type="submit" id="draft_sub" value="保存" style="margin-right: 100px;width: 130px;height: 35px">  
                    <input class="btn btn-sm btn-dropbox " type="submit" id="real_sub" value="提交brief订单" style="width: 130px;height: 35px"></div>');
        } else {
            $form->html('<div style="text-align:center;padding-top: 30px" >
                    <input class="btn btn-sm btn-success " type="submit" id="draft_sub" value="保存" style="margin-right: 100px;width: 130px;height: 35px">  
                    <input class="btn btn-sm btn-dropbox " type="submit" id="real_sub" value="提交brief订单" style="width: 130px;height: 35px"></div>');
        }
        $form->action('/admin/communityMcn/briefInfo/save');
        return $content
            ->header('创建订单')
            ->breadcrumb(['text' => 'MCN项目管理', 'url' => ''], ['text' => '创建订单'])
            ->row($form->render());
    }

    //展示页（只读页面）
    public function onlyView(Content $content, $id = 0)
    {
        self::$isBusiness = AdminRole::isBusiness();
        $info = Brief::getByid($id);
        $info['expect_start_time'] = date('Y-m-d', $info['expect_start_time']);
        $info['expect_end_time'] = date('Y-m-d', $info['expect_end_time']);
        $info['one_price_num'] = $info['one_price_num']/100;
        $info['price_goods_price'] = $info['price_goods_price']/100;
        $form = new Form($info);
        $form->hidden('id', 'brief ID');
        $form->hidden('status', '状态');
        $form->text('project_name', '项目名称')->readonly();
        $form->select('brand_inner', '站内/站外')->options(Brief::BRAND_INNER_LIST)
            ->when('=', 1, function ($form) {
                $brandList = sBrief::getBrandList();
                $form->select('popularize_brand_id', '推广品牌')->options($brandList)->readonly();
            })->when('=', 2, function ($form) {
                $form->text('popularize_brand_name', '推广品牌')->readonly();
            })->readonly();
        $form->text('store_id', '店铺ID')->readonly();
        $form->text('store_name', '店铺名称')->readonly();
        $form->text('order_id', '订单ID')->readonly();
        $form->multipleSelect('collaborative_area', '合作领域')->options(Brief::AREA_LIST)->readonly();
        $form->text('goods_id', '主推商品ID')->readonly();
        $form->text('goods_trait', '主推商品卖点')->placeholder('请输入商品卖点')->readonly();
        $form->text('popularize_product', '推广产品')->readonly();
        $form->textarea('product_url', '产品链接')->readonly();
        $form->select('purpose', '传播目的')->options(Brief::PURPOSE_LIST)
            ->when('=', 4, function ($form) {
                $form->text('purpose_other', '其他传播目的')->readonly();
            })->readonly();
        $form->radio('cooperate_style', '合作方式')->options(Brief::COOPERATE_STYLE_LIST)->readonly();
        $form->dateRange('expect_start_time', 'expect_end_time', '期望发布时间')->readonly();
        $form->select('price_style', '报价方式')->options(Brief::PRICE_STYLE_LIST)
            ->when('=', Brief::STYLE_PRICE, function ($form) {
                $form->select('one_price_type', '一口价报价方式')->options(Brief::ONE_PRICE_TYPE_LIST)->readonly();
                $form->text('one_price_num', '一口价（元）')->readonly();
            })
            ->when('=', Brief::STYLE_GOODS, function ($form) {
                $form->text('price_goods_num', '主推商品提供件数')->readonly();
                $form->text('price_goods_price', '主推商品提供价格（元）')->readonly();
            })->readonly();
        $form->radio('content_type', '上传内容类型')->options(Brief::CONTENT_TYPE_LIST)->readonly();
        $form->textarea('words_demand', '文字需求')->readonly();
        $form->textarea('pictures_demand', '图片需求')->readonly();
        $form->textarea('videos_demand', '视频需求')->readonly();
        $form->textarea('creator_require', '创作者要求')->readonly();
        $form->textarea('remarks', '备注')->readonly();
        Admin::script($this->saveScript());
        $form->disableSubmit();
        $form->disableReset();
        if ((self::$isBusiness || $info['admin_uid'] == Admin::user()->id) && $info['status'] == Brief::STATUS_CHANGE) {
            $url = '/admin/communityMcn/briefInfo/' . $id . '/edit';
            $form->html('<div style="text-align:center;padding-top: 30px" >
                    <a href="' . $url . '"><input class="btn btn-sm btn-soundcloud " value="修改" style="margin-right: 100px;width: 130px;height: 35px"></a></div>');
        }

        if(!self::$isBusiness && $info['status'] == Brief::STATUS_CHECK){
            $url = '/admin/communityMcn/suggestion/create?b_id=' . $id;
            $form->html('<div style="text-align:center;padding-top: 30px" >
                    <a href="' . $url . '"><input class="btn btn-sm btn-soundcloud " value="添加修改意见" style="margin-right: 100px;width: 130px;height: 35px"></a>
                    <input class="btn btn-sm btn-success " type="submit" id="" value="确认订单信息" style="margin-right: 100px;width: 130px;height: 35px"> 
                    </div>');
            $form->confirm('确认审核通过');
            $form->action('/admin/communityMcn/briefInfo/approved');
        }

        if(!self::$isBusiness && $info['status'] == Brief::STATUS_DISPATCH)
        {
            $url = '/admin/communityMcn/inviteMember/'.$id.'/index/create';
            $form->html('<div style="text-align:center;padding-top: 30px" >
                    <a href="' . $url . '"><input class="btn btn-sm btn-soundcloud " value="填写kol名单" style="margin-right: 100px;width: 130px;height: 35px"></a>
                    </div>');
        }

        return $content
            ->header('创建订单')
            ->breadcrumb(['text' => 'MCN项目管理', 'url' => ''], ['text' => '订单详情'])
            ->row($form->render());
    }


    public function saveScript()
    {
        return <<<SCRIPT
         $('#draft_sub').unbind('click').click(function(){
           $(".status").attr("value",'1');
         });
         $('#real_sub').unbind('click').click(function(){
           $(".status").attr("value",'2');
         });
        SCRIPT;
    }


    public static function save(Request $request)
    {
        $param = $request->all();
        $data['price_style'] = $param['price_style'];
        $data = array();
        $data['admin_uid'] = admin::user()->id;
        $data['order_id'] = self::getOrderId(); //todo
        $data['project_name'] = $param['project_name'];
        if (!ParamsCheck::checkLen($data['project_name'], 12)) {
            throw new InputErrorException('字数不得超过12个', InputErrorException::DEFAULT_CODE, 'project_name');
        }
        $data['brand_inner'] = $param['brand_inner'];
        //站内站外
        if ($data['brand_inner'] == Brief::INNER_BRAND) {
            if (!$param['popularize_brand_id']) {
                throw new InputErrorException('请输入必填项', InputErrorException::DEFAULT_CODE, 'popularize_brand_id');
            }
            $data['popularize_brand_id'] = $param['popularize_brand_id'];
        } else {
            if (!$param['popularize_brand_name']) {
                throw new InputErrorException('请输入必填项', InputErrorException::DEFAULT_CODE, 'popularize_brand_name');
            }
            $data['popularize_brand_name'] = $param['popularize_brand_name'];
            if (!$param['store_id']){
                throw new InputErrorException('请输入必填项', InputErrorException::DEFAULT_CODE, 'store_id');
            }
            if (!$param['store_name']){
                throw new InputErrorException('请输入必填项', InputErrorException::DEFAULT_CODE, 'store_name');
            }
        }
        $data['store_id'] = $param['store_id'];
        $data['store_name'] = $param['store_name'];
        if ($data['store_name'] && !ParamsCheck::checkLen($data['store_name'], 12)) {
            throw new InputErrorException('字数不得超过12个', InputErrorException::DEFAULT_CODE, 'store_name');
        }
        $data['collaborative_area'] = join(',', array_unique($param['collaborative_area']));
        $data['popularize_product'] = $param['popularize_product'];
        if (!ParamsCheck::checkLen($data['popularize_product'], 12)) {
            throw new InputErrorException('字数不得超过12个', InputErrorException::DEFAULT_CODE, 'popularize_product');
        }
        $data['goods_id'] = $param['goods_id'];
        $data['goods_trait'] = $param['goods_trait'];
        $data['product_url'] = $param['product_url'];
        $data['purpose'] = $param['purpose'];
        if ($data['purpose'] == Brief::PURPOSE_OTHER) {
            if (!$param['purpose_other']) {
                throw new InputErrorException('请输入必填项', InputErrorException::DEFAULT_CODE, 'purpose_other');
            }
            $data['purpose_other'] = $param['purpose_other'];
        }

        $data['cooperate_style'] = $param['cooperate_style'];
        $data['expect_start_time'] = strtotime($param['expect_start_time']);
        $data['expect_end_time'] = strtotime($param['expect_end_time']);
        $data['price_style'] = $param['price_style'];

        if ($data['price_style'] == Brief::STYLE_PRICE) {
            if (!$param['one_price_type']) {
                throw new InputErrorException('请输入必填项', InputErrorException::DEFAULT_CODE, 'one_price_type');
            }
            $data['one_price_type'] = $param['one_price_type'];
            if (!$param['one_price_num']) {
                throw new InputErrorException('请输入必填项', InputErrorException::DEFAULT_CODE, 'one_price_num');
            }
            if(!is_numeric($param['one_price_num'])){
                throw new InputErrorException('请输入正确价格', InputErrorException::DEFAULT_CODE, 'one_price_num');
            }
            $data['one_price_num'] = $param['one_price_num'] * 100;
        } else {
            if (!$param['price_goods_num']) {
                throw new InputErrorException('请输入必填项', InputErrorException::DEFAULT_CODE, 'price_goods_num');
            }
            if(!is_numeric($param['price_goods_num'])){
                throw new InputErrorException('请输入正确数量', InputErrorException::DEFAULT_CODE, 'price_goods_num');
            }
            $data['price_goods_num'] = $param['price_goods_num'];
            if (!$param['price_goods_price']) {
                throw new InputErrorException('请输入必填项', InputErrorException::DEFAULT_CODE, 'price_goods_price');
            }
            if(!is_numeric($param['price_goods_price'])){
                throw new InputErrorException('请输入正确价格', InputErrorException::DEFAULT_CODE, 'price_goods_price');
            }
            $data['price_goods_price'] = $param['price_goods_price'] * 100;
        }

        $data['content_type'] = $param['content_type'];
        $data['words_demand'] = $param['words_demand'];
        $data['pictures_demand'] = $param['pictures_demand'];
        $data['videos_demand'] = $param['videos_demand'];

        if($data['content_type'] == Brief::CONTENT_TYPE_WP){
            if (!$param['words_demand']) {
                throw new InputErrorException('请输入必填项', InputErrorException::DEFAULT_CODE, 'words_demand');
            }
            if (!$param['pictures_demand']) {
                throw new InputErrorException('请输入必填项', InputErrorException::DEFAULT_CODE, 'pictures_demand');
            }
        }
        if($data['content_type'] == Brief::CONTENT_TYPE_V){
            if (!$param['videos_demand']) {
                throw new InputErrorException('请输入必填项', InputErrorException::DEFAULT_CODE, 'videos_demand');
            }
        }
        if (!ParamsCheck::checkLen($data['words_demand'], 500) && $data['words_demand']) {
            throw new InputErrorException('字数不得超过500个', InputErrorException::DEFAULT_CODE, 'words_demand');
        }
        if (!ParamsCheck::checkLen($data['pictures_demand'], 500) && $data['pictures_demand']) {
            throw new InputErrorException('字数不得超过500个', InputErrorException::DEFAULT_CODE, 'pictures_demand');
        }
        if (!ParamsCheck::checkLen($data['videos_demand'], 500) && $data['videos_demand']) {
            throw new InputErrorException('字数不得超过500个', InputErrorException::DEFAULT_CODE, 'videos_demand');
        }

        $data['creator_require'] = $param['creator_require'];
        if (!ParamsCheck::checkLen($data['creator_require'], 300)) {
            throw new InputErrorException('字数不得超过300个', InputErrorException::DEFAULT_CODE, 'creator_require');
        }
        $data['remarks'] = $param['remarks'];
        if (!ParamsCheck::checkLen($data['remarks'], 500)) {
            throw new InputErrorException('字数不得超过500个', InputErrorException::DEFAULT_CODE, 'remarks');
        }
        $data['add_time'] = time();
        $data['edit_time'] = time();
        $data['status'] = $param['status'];
        if ($param['status'] == Brief::STYLE_GOODS) {
            if(!$data['invite_time']){
                $data['invite_time'] = time();
                $data['close_time'] = Brief::CLOSE_SECONDS + time();
            }
        }
        if ($param['id']) {
            $result = Brief::updateById($param['id'], $data);
        } else {
            $result = Brief::addData($data);
        }
        if ($result) {
            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return redirect('/admin/communityMcn/briefInfo/index')->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '保存失败'
            ]);
            return back()->with(compact('error'));
        }
    }

    public static function approved(Request $request)
    {
        $param = $request->all();
        $data = ['status' => Brief::STATUS_DISPATCH,'close_time'=> Brief::CLOSE_SECONDS + time()];
        $result = Brief::updateById($param['id'], $data);
        if ($result) {
            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return back()->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '保存失败'
            ]);
            return back()->with(compact('error'));
        }
    }

    public static function getOrderId(){
        $orderId = Brief::getLikeOrder(time());
        if($orderId){
            $num = substr($orderId,3) + 1;
            return 'hhz' . $num;
        }
        return 'hhz'.time().'0000000001';
    }

}